package com.neusoft.yuejian12.yuejian_12.base;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Shinelon on 2017/4/10.
 */

public class RetrofitCallBuilder {

    private Retrofit retrofit;



    public static RetrofitCallBuilder getInstance() {

        return new RetrofitCallBuilder();
    }

    public RetrofitCallBuilder baseUrl(String baseUrl) {

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return this;
    }

    public Call buildCall(Class serviceCls,
                          String methodName,
                          Object[] parameterValues) {

        Object s = retrofit.create(serviceCls);
        Call call = null;

        if (parameterValues == null || parameterValues.length == 0) {

            Method method = null;
            try {
                method = serviceCls.getMethod(methodName, new Class[]{});
                call = (Call) method.invoke(s, new Object[]{});
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        } else {

            Class[] parameterTypes = new Class[parameterValues.length];

            for (int i = 0; i < parameterValues.length; i++) {

                parameterTypes[i] = parameterValues[i].getClass();
            }

            Method method = null;
            try {
                method = serviceCls.getMethod(methodName, parameterTypes);
                call = (Call) method.invoke(s, parameterValues);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return call;
    }

    public <T> void bindCallback(Call<T> call, RetrofitCallback<T> callback) {
        call.enqueue(callback);
    }

}
